package com.zenith.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zenith.user.mapper.UserRoleMapper;
import com.zenith.user.po.domain.RolePermission;
import com.zenith.user.po.domain.UserRole;
import com.zenith.user.po.dto.UserRoleDTO;
import com.zenith.user.service.RolePermissionService;
import com.zenith.user.service.UserRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zenith.common.result.PageResult;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 用户角色关联 业务实现
 *
 * @author makejava
 * @since 2025-08-15
 */
@Slf4j
@Service
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole> implements UserRoleService {
    @Autowired
    private RolePermissionService rolePermissionService;

    @Override
    public PageResult<UserRole> getUserRolePage(UserRoleDTO query) {
        // 创建分页对象
        Page<UserRole> page = new Page<>(query.getPageNum() != null ? query.getPageNum() : 1, 
                                       query.getPageSize() != null ? query.getPageSize() : 10);
        // 执行分页查询
        Page<UserRole> pageResult = lambdaQuery().page(page);
        // 封装返回结果
        return PageResult.ofPage(page.getCurrent(), page.getSize(), pageResult.getTotal(), pageResult.getRecords());
    }

    @Override
    public Set<String> getUserRoleIds(Long userId) {
        // 执行查询
        List<UserRole> userRoles = lambdaQuery().eq(UserRole::getUserId, userId).list();
        Set<String> roleIds = userRoles.stream().map(userRole -> String.valueOf(userRole.getRoleId())).collect(Collectors.toSet());
        return roleIds;
    }

    @Override
    public Set<String> getUserPermissionIds(Long userId) {
        // 执行查询
        List<UserRole> userRoles = lambdaQuery().eq(UserRole::getUserId, userId).list();
        // 查询用户角色的权限ID
        LambdaQueryWrapper<RolePermission> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RolePermission::getIsDelete, 0);
        // 查询用户角色关联的权限
        queryWrapper.in(RolePermission::getRoleId, userRoles.stream().map(userRole -> userRole.getRoleId()).collect(Collectors.toList()));
        List<RolePermission> rolePermissions = rolePermissionService.list(queryWrapper);
        Set<String> permissionIds = rolePermissions.stream().map(rolePermission -> String.valueOf(rolePermission.getPermissionId())).collect(Collectors.toSet());
        return permissionIds;
    }
}